﻿using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using OfficeOpenXml;


namespace Core
{
    public class Core
    {
        public void Run()
        {
            TfsConfigurationServer configurationServer =
            TfsConfigurationServerFactory.GetConfigurationServer(new Uri(Configuration.TfsUri));

            CatalogNode catalogNode = configurationServer.CatalogNode;

            ReadOnlyCollection<CatalogNode> tpcNodes = catalogNode.QueryChildren(
                new Guid[] { CatalogResourceTypes.TeamProject },
                true, CatalogQueryOptions.None);

            var projectNode = tpcNodes.Where(p => p.Resource.DisplayName == Configuration.Project).FirstOrDefault();

            var tfstpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(Configuration.TfsUri));
            var workItemStore = tfstpc.GetService<WorkItemStore>();

            StringBuilder queryString = new StringBuilder("SELECT * FROM WorkItem WHERE ");
            queryString.AppendFormat("[System.TeamProject] = 'IEC' AND [System.ChangedDate] >= '{0}'",
                Configuration.ReportDate.ToShortDateString());
            Query wiQuery = new Query(workItemStore, queryString.ToString());
            WorkItemCollection workItemCollection = wiQuery.RunQuery();

            Trace.WriteLine(workItemCollection.Count + " work items selected.");

            var excelPackage = OpenExcelFileWithWaiting(Configuration.ReportFilePath);

            var dailyReport = new DailyReport(tfstpc, excelPackage);
            dailyReport.Build(workItemCollection);

            //var closedReport = new ResolvedReport();
            //closedReport.Build(workItemCollection);

            excelPackage.Save();
        }

        /// <summary>
        /// Try to open excel file. If the file is busy, repeat attempt in 1 second. Try during 30 minutes.
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static ExcelPackage OpenExcelFileWithWaiting(string filePath)
        {
            for(int i=0; i<1800; i++)
            {
                try
                {
                    var file = new FileInfo(filePath);
                    return new ExcelPackage(file);
                }
                catch (IOException ex)
                {
                    Trace.WriteLine(ex.Message);
                }
                System.Threading.Thread.Sleep(1000);
            }
            return null;
        }
    }
}
